package com.ruoyi.web.core.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;
/**
 * @Program: RuoYi-Vue-chy->AsyncConfig
 * @Description: 配置类中定义一个ThreadPoolTaskExecutor Bean
 * @Author: hongyu.chen
 * @Date: 2025-03-06 16:30
 * @Version： 1.0
 **/
@EnableAsync
@Configuration
public class AsyncConfig {

    @Bean(name = "taskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        //获取 CPU 核心数
        int cpuCoreCount = Runtime.getRuntime().availableProcessors();
        // 设置核心线程数
        executor.setCorePoolSize(cpuCoreCount * 2);

        // 设置最大线程数
        executor.setMaxPoolSize(cpuCoreCount * 4);

        // 设置队列容量
        executor.setQueueCapacity(100);

        // 设置线程空闲时间（秒）
        executor.setKeepAliveSeconds(60);

        // 设置线程名称前缀
        executor.setThreadNamePrefix("AsyncTask-");

        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        // 初始化线程池
        executor.initialize();

        return executor;
    }
}
